package com.mer.filter;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


//@Component
public class LoginFilter implements Ordered, GlobalFilter {

    @Resource
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)  {
        //获取后台请求头中携带的token数据
        String token = exchange.getRequest().getHeaders().getFirst("token");
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //判断token中是否有数据 以及redis缓存数据库中是否有相关数据

        if(StringUtils.isNotEmpty(token)&&redisTemplate.opsForValue().get(token)!=null){
            //不为空就放行
            return  chain.filter(exchange);
        }
        //判断是否为登录请求
        if(exchange.getRequest().getPath().toString().contains("/sso/admin/login")){
            //是请求路径就放行
            return chain.filter(exchange);
        }
        //如果未登录，自定义响应内容
        DataBuffer buffer=null;
        try {
//            CommonResult commonResult=new CommonResult(401,"请先登录",null);
            Map<String,Object> commonResult=new HashMap<>();
            commonResult.put("code",401);
            commonResult.put("msg","请先登录");
            byte[] datas = JSON.toJSONString(commonResult).getBytes("utf-8");
            buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(buffer));

    }


    //拦截器的优先级，返回值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}